package com.itheima.fillter;

import io.netty.util.internal.StringUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 全局过滤器
 */
@Component
public class LoginFilter implements GlobalFilter {


    /**
     * 过滤方法
     * @param exchange 封装请求对象 和响应对象
     * @param chain  过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.检查请求对象是否包含access-token参数，及参数的值是否为token
        Map<String, String> param = request.getQueryParams().toSingleValueMap();

        String token = param.get("access-token");
        // 包含且 值为admin  ==》放行请求
        if (!StringUtils.isEmpty(token)&&"admin".equals(token)){
            return chain.filter(exchange);
        }else{
            // 不包含且 值为admin  ==》终止相应
            ServerHttpResponse response = exchange.getResponse();

            //设置未登陆状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            return response.setComplete();//终止相应
        }


    }
}
